package com.training1.core.common.log;

import java.util.Arrays;
import java.util.List;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.training1.core.common.utils.StringUtils;
import com.wordnik.swagger.annotations.ApiOperation;

@Aspect
@Component
public class ApiControllerLog {

	private static final Logger log = LoggerFactory.getLogger("api.access");
	
	@Pointcut("execution(* com.training1.api.controller.*.*(..))")  
    public void apiControllerLog() {  
    } 
	
	@Around("apiControllerLog()&&@annotation(api)")
	public Object doAround(ProceedingJoinPoint pjd,ApiOperation api) throws Throwable {
		String methodName = pjd.toShortString();
		String methodChineseName = null;
		if(api!=null){
			methodChineseName = api.value();
		}
		boolean containPassword = StringUtils.indexOfIgnoreCase(pjd.getSignature().getName(), "password")!=-1;
		List<Object> args = Arrays.asList(pjd.getArgs());
		long now = System.currentTimeMillis();
		Object ret = null;
		try{
			if(args.size()>0){
				ret = pjd.proceed(pjd.getArgs());
			}else{
				ret = pjd.proceed();
			}
		}catch(Throwable e){
			long cost = System.currentTimeMillis()-now;
			if(containPassword){
				args=null;
			}
			log.error("{},执行{}出错,参数为{},错误信息:{},耗时{}毫秒", methodChineseName,methodName,args,e.getMessage(),cost);
			log.error("接口出错,",e);
			throw e;
		}
		if(containPassword){
			args=null;
		}
		long cost = System.currentTimeMillis()-now;
		log.info("{},执行{}完成，入参为{},返回{},执行耗时{}毫秒", methodChineseName,methodName,args,ret,cost,ret);
		return ret;
	}
}
